package edu.biwu.req;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@WebServlet("/req/upload01")
@MultipartConfig
public class ReqUploadDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //如果上传的中文文件名乱码请使用以下语句
        //request.setCharacterEncoding("UTF-8");

        //1.通过request对象来获取Part接口实现类对象(改对象中封装了上传文件的相关信息)
        Part uploadFile = request.getPart("uploadFile");

        //2.通过Part接口的实现类对象获取上传文件的相关信息
		/*System.out.println(uploadFile.getSubmittedFileName());
		System.out.println(uploadFile.getContentType());
		System.out.println(uploadFile.getSize());
		System.out.println(uploadFile.getName());*/
        String fileName = uploadFile.getSubmittedFileName();

        //3.保证存储文件名唯一,可以让用户重复上传文件
        String extensive = fileName.substring(fileName.lastIndexOf('.'));
        String newFileName = UUID.randomUUID() + extensive;

        //4.将上传的文件写入到服务端的某个位置,存储上传文件
        File dir = new File("D:/upload");
        if (!dir.exists()){
            dir.mkdirs();
        }
        uploadFile.write(dir + "/" + newFileName);//直接将上传的文件写入指定位置

        //5.上传成功后,响应上传成功提示
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(fileName + " 文件上传成功");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
